package shuaige.jdk.多线程.concurrent.completableFuture;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

public class 并行运行多个Futures示例2 {
    private static final List<String> list = Arrays.asList("王小波书店", "杭州沈记古旧书店", "猫的天空之城概念书店", "纯真年代书吧", "南山书屋", "西西弗书店", "新华书店", "钟书阁", "云门书屋");
    private static final ExecutorService executor = Executors.newFixedThreadPool(list.size(), r -> {
        Thread thread = new Thread(r);
        //守护线程不会组织程序的终止
        thread.setDaemon(true);
        return thread;
    });

    public static void main(String[] args) {
        并行运行多个Futures示例2 并行运行多个Futures示例2 = new 并行运行多个Futures示例2();
        并行运行多个Futures示例2.test12();
    }

    public void test12() {
        System.out.println("当前机器有" + Runtime.getRuntime().availableProcessors() + "个可用的处理器, 当前处理异步请求的线程池大小为 " + Math.min(list.size(), 100));
        long start = System.nanoTime();
        List<CompletableFuture<String>> futures = list.stream()
                .map(str -> {
                    return CompletableFuture.supplyAsync(() -> this.calculateLength(str), executor);
                })
                .collect(Collectors.toList());
        System.out.println("get futures " + (System.nanoTime() - start) / 1000_000 + " msecs");
        String result = futures.stream()
                .map(CompletableFuture::join)
                .collect(Collectors.joining(",", "[", "]"));
        System.out.println("get result " + (System.nanoTime() - start) / 1000_000 + " msecs");
        System.out.println(result);
    }

    public String calculateLength(String str) {
        delay();
        return str;
    }

    public void delay() {
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
